import { defineStore } from 'pinia';
import {
  login as userLogin,
  logout as userLogout,
  // getUserInfo,
} from '@/api/user/user';
import { setToken, clearToken } from '@/utils/auth';
import { setUserInfo, getUserInfo, clearUserInfo } from '@/utils/user';
import { removeRouteListener } from '@/utils/route-listener';
// import { UserState } from './types';
import { UserData as UserState, LoginData } from '@/api/user/user.d'
import useAppStore from '../app';

const useUserStore = defineStore('user', {
  persist: true,
  state: (): UserState => ({
    token: '',
    company: [],
    createTime: undefined,
    id: undefined,
    mobile: '',
    shortCode: '',
    status: undefined,
    updateTime: undefined,
    userName: '',
    role: "admin",//用户查看模式：管理员和标注用户
    permCodes: [] as string[],//登录用户的所有权限code
    roleList: [],//后端配置的登录用户的角色列表
    permList: [],//后端配置的登录用户的权限列表
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    switchRoles() {
      // return () => {
      //   this.role = this.role === 'user' ? 'admin' : 'user';
      //   this.setInfo({
      //     role: this.role
      //   });
      //   return this.role
      // }
      return new Promise((resolve) => {
        this.role = this.role === 'user' ? 'admin' : 'user';
        this.setInfo({
          role: this.role
        });
        resolve(this.role);
      });
    },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async info() {
      // const res = await getUserInfo();
      // this.setInfo(res.data);
      const res = getUserInfo();
      this.setInfo(res && JSON.parse(res || '{}'));
    },

    // Login
    login: async function (loginForm: LoginData) {
      try {
        const res = await userLogin(loginForm);
        const { token, roleList, permList, ...user } = res.data;
        setToken(token);
        const newUser = {
          ...user,
          role: 'admin'
        }
        let permCodes = permList.map(it => it.code)/*.filter(code => !['A040401001'].includes(code))*/
        /*permCodes.push('A020000000','A020200000','A020201000','A020201001','A020201002','A020201003','A020201004','A020201005')*/
        this.$state = {
          ...newUser,
          roleList,permList,
          permCodes
        };
        // console.log('userState', this.$state)
      } catch (err) {
        clearToken();
        clearUserInfo();
        throw err;
      }
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      clearUserInfo();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      try {
        await userLogout();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
